﻿Module Main

  Private LineFeed As Char = Environment.NewLine.Chars(Environment.NewLine.Length - 1)

  Sub Main()
    Dim FilePaths As New List(Of String)
    If Environment.GetCommandLineArgs().Length > 1 Then
      FilePaths.AddRange(Environment.GetCommandLineArgs().Where(Function(Current As String) File.Exists(Current)))
      For Each Item In Environment.GetCommandLineArgs().Where(Function(Current As String) Directory.Exists(Current))
        FilePaths.AddRange(Directory.GetFiles(Item))
      Next
    Else
      FilePaths.AddRange(Directory.GetFiles(New FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory.FullName))
    End If

    For Each FilePath In FilePaths.Where(Function(Current As String) File.Exists(Current) AndAlso Path.GetExtension(Current).ToLower.StartsWith(".xls", StringComparison.InvariantCultureIgnoreCase))
      Console.Write("Converting " & Path.GetFileName(FilePath) & "... ")

      Dim Buffer As New System.Text.StringBuilder("{")

      Using Source As New ExcelPackage(New FileInfo(FilePath))
        For Each Sheet In Source.Workbook.Worksheets
          Buffer.AppendFormat("""{0}"":[", Sheet.Name)

          For r As Integer = 1 To Sheet.Dimension.End.Row
            If r > 1 Then
              Buffer.Append(",")
            End If
            Buffer.Append("[")
            For c As Integer = 1 To Sheet.Dimension.End.Column
              If c > 1 Then
                Buffer.Append(",")
              End If
              Dim Cell As ExcelRange = Sheet.Cells(r, c)
              If Cell.Value IsNot Nothing Then
                Buffer.AppendFormat("""{0}""", Escape(Cell.Value.ToString()))
              ElseIf Cell.Formula IsNot Nothing Then
                Buffer.AppendFormat("""{0}""", Escape(Cell.Formula))
              Else
                Buffer.Append("""""")
              End If
            Next
            Buffer.Append("]")
          Next

          Buffer.Append("],")
        Next
      End Using

      If Buffer.Chars(Buffer.Length - 1) = "," Then
        Buffer.Remove(Buffer.Length - 1, 1)
      End If
      Buffer.Append("}")

      Using Writer As New StreamWriter(Path.ChangeExtension(FilePath, "json"), False, System.Text.Encoding.UTF8)
        Writer.Write(Buffer)
      End Using

      Console.ForegroundColor = ConsoleColor.Green
      Console.WriteLine("done")
      Console.ResetColor()
    Next

    Console.WriteLine("Terminated.")
  End Sub

  Private Function Escape(Input As String) As String
    Dim Buffer As New System.Text.StringBuilder(Input)
    Buffer.Replace("""", "\""")
    Buffer.Replace("\", "\\")
    Buffer.Replace(LineFeed, "\n")
    Buffer.Replace(vbTab, "\t")
    Return Buffer.ToString().Trim()
  End Function

End Module
